//
//  LDHomeTableViewController.swift
//  Weibo201655
//
//  Created by pro on 16/5/5.
//  Copyright © 2016年 LeeDan. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

class LDHomeTableViewController: LDBaseTableViewController {
    
    //MARK:----------------------- 属性 ----------------------------------//
    //模型数组属性
    var statusList: [LDStatus]? {
        didSet {
//            tableView.reloadData()
        }
    }
    //cellID
    private let cellID = "statusCellID"
    
    
    //MARK:----------------------- 系统方法 ----------------------------------//
    override func viewDidLoad() {
        super.viewDidLoad()

        //MARK: 用户没有登录，就不执行下面操作
        if sharedUserAccount == nil {
            print("用户没登录，不加载首页微博")
            return
        }
        
        //设置导航栏
        setNavBar()
        
        //刷新控件设置
        setRefreshControl()
        
        //设置tableView
        setupTableView()
    }
    
    //MARK:----------------------- 自定义方法 ----------------------------------//
    func setRefreshControl() {
        //刷新
        refreshControl = LDRefreshControl()
        refreshControl?.addTarget(self, action: "loadNewStatuses", forControlEvents: UIControlEvents.ValueChanged)
        
        //MARK: 下拉加载微博数据
        // 开始刷新, 只会让刷新控件进入刷新状态,并不会触发UIControlEvents.ValueChanged事件
        refreshControl?.beginRefreshing()
        
        // 我们主动触发refreshControl的UIControlEvents.ValueChanged
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    func setupTableView() {
        //注册cell
        tableView.registerClass(LDStatusCell.self, forCellReuseIdentifier: cellID)
        //预估行高
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //取消选中
        tableView.allowsSelection = false
        
        //MARK: 上拉加载微博数据
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatuses()
        }
        
        //下拉刷新好丑
//        tableView.addPullToRefreshWithActionHandler { () -> Void in
//            print("pull")
//        }
    }
    
    //MARK: 加载最新微博数据
    func loadNewStatuses() {
       
        let sinceID = Int(statusList?.first?.id ?? 0)
        LDStatusViewModel.loadStatusModels(sinceID, max_id: 0) { (statuses, error) -> () in
            
            //结束刷新动画
            self.refreshControl?.endRefreshing()
            
            if  (error != nil) {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                print(error)
                return
            }
            //statuses有可能为nil，或者是空数组
            let count = statuses?.count ?? 0
            if count  == 0 {
                return
            }
            //刷新微博
            if sinceID == 0 {
                self.statusList = statuses
            }else {
                self.statusList = statuses! + self.statusList!
            }
            //print(self.statusList)
            //OC使用
            self.tableView.reloadData()
        }
        
    }
    
    //MARK: 加载旧微博
    func loadMoreStatuses() {

        let maxID = Int(statusList?.last?.id ?? 0)

        LDStatusViewModel.loadStatusModels(0, max_id: maxID) { (statuses, error) -> () in
            
            //结束刷新动画
            self.tableView.infiniteScrollingView.stopAnimating() // 让第SVPullToRefresh隐藏.
            
            if  (error != nil) {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                print(error)
                return
            }
            //statuses有可能为nil，或者是空数组
            let count = statuses?.count ?? 0
            if count  == 0 {
                return
            }
            //刷新微博
            self.statusList = self.statusList! + statuses!
            //print(self.statusList)
            //OC使用
            self.tableView.reloadData()
        }

    }
    
    //MARK: 设置导航栏
    func setNavBar() {
        //设置导航栏左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem.barButtonItem("navigationbar_pop")
        //标题栏
        let btnView =  LDTitleButton()
        btnView.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal)
        //显示昵称
        if let name = sharedUserAccount?.screen_name {
            btnView.setTitle(name, forState: UIControlState.Normal)
        } else {
            btnView.setTitle("我的标题", forState: UIControlState.Normal)
        }
        btnView.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        btnView.sizeToFit()//尺寸
        btnView.addTarget(self, action: "btnViewClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = btnView


    }

    //MARK: 按钮点击事件
    //MARK: titleView点击动画
    func btnViewClick(btn: LDTitleButton) {
        btn.selected = !btn.selected
        
        //动画：箭头旋转
        UIView.animateWithDuration(0.25) { () -> Void in
            btn.imageView?.transform = btn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
        // 按钮选中的时候弹出Popover
        if !btn.selected {
            return
        }
        //加载popVC控制器
        let popVC = LDPopViewController()
        popVC.modalPresentationStyle = UIModalPresentationStyle.Popover
        popVC.popoverPresentationController?.sourceView = navigationItem.titleView
        popVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
//        popVC.preferredContentSize = CGSizeMake(300, 400)
        popVC.popoverPresentationController?.delegate = self
        presentViewController(popVC, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
extension LDHomeTableViewController {
    
    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! LDStatusCell
        
        let status = statusList![indexPath.row]
        
        cell.status = status
        
        return cell
        
    }
    
//    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        return 80
//    }
}

extension LDHomeTableViewController: UIPopoverPresentationControllerDelegate {
    // 让iPhone上面可以显示popover效果
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    // popover关闭时调用
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        //旋转箭头朝上
        UIView.animateWithDuration(0.25) { () -> Void in
            let btn = self.navigationItem.titleView as! LDTitleButton
            self.btnViewClick(btn)
        }
    }
}
